package com.midian.service.activity.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.midian.common.dao.BaseDaoBySql;
import com.midian.common.dao.OrderHelper;
import com.midian.common.dao.SearchHelper;
import com.midian.common.dao.SearchHelper.Type;
import com.midian.common.exception.BizException;
import com.midian.common.pager.Pager;
import com.midian.common.system.SysStatic;
import com.midian.model.activity.Activity;
import com.midian.model.activity.ActivityUser;
import com.midian.service.activity.IActivityService;
import com.midian.service.common.BaseService;

/**
 * 活动业务实现类
 * 
 * @author Mengfh
 * 
 */
@Service("activityService")
public class ActivityServiceImpl extends BaseService implements IActivityService {
	/** 活动DAO */
	private BaseDaoBySql<Activity> activityDAO;

	@Resource(name = "activityDAO")
	public void setActivityDAO(BaseDaoBySql<Activity> activityDAO) {
		this.activityDAO = activityDAO;
	}

	@Override
	public Activity add(Activity target) throws BizException {
		this.activityDAO.add(target);
		return target;
	}

	@Override
	public void update(Activity target) throws BizException {
		this.activityDAO.updateByConvertHql(target);
	}

	@Override
	public void delete(Serializable id) throws BizException {
		this.activityDAO.delete(id);
	}

	@Override
	public void delete(Serializable[] ids) throws BizException {
		this.activityDAO.delete(ids);
	}

	@Override
	public Activity get(Serializable id) throws BizException {
		return this.activityDAO.get(id);
	}

	@Override
	public List<Activity> showList(Activity target, Pager pager, List<OrderHelper> helper) throws BizException {
		return this.activityDAO.find(target, getSearchHelper(), helper, pager);
	}

	@Override
	public void opDelFlag(Serializable[] ids, Integer status) throws BizException {
		this.activityDAO.opDelFlag(ids, status);
	}

	@Override
	protected List<SearchHelper> getSearchHelper() {
		String[] attrs = {};
		Type[] types = {};
		return SearchHelper.getSearchList(attrs, types);
	}

	@Override
	public List<Activity> getActivities(String lon, String lat, String time_filter,
			String type_filter, String age_filter, String distance_filter, String key, Pager pager) {
		List<Activity> activities = null;
		StringBuilder sql = new StringBuilder();
		sql.append("select a.id,a.coverPicId,a.title,a.beginTime,aType.typeName as 'typeName',o.name as 'organizationName',");
		sql.append("a.adultPrice,a.childPrice,a.ages,a.activityAddress,a.activityAddressLon,");
		sql.append("a.activityAddressLat");

		if (StringUtils.isNotBlank(lat) && StringUtils.isNotBlank(lon)) {
			// 距离
			sql.append(",round(6371.393*2*asin(sqrt(pow(sin((" + lat + "*pi()/180-a.activityAddressLat*pi()/180)/2),2)");
			sql.append("+cos(" + lat + "*pi()/180)*cos(a.activityAddressLat*pi()/180)* pow(sin((" + lon);
			sql.append("*pi()/180-a.activityAddressLon*pi()/180)/2),2)))*1000) as 'distance' ");
		}

		sql.append(" from activity a ");
		sql.append("left join activity_type aType on aType.id = a.typeId ");
		sql.append("left join organization o on o.id = a.organizationId ");
		sql.append("where a.deleteFlag = ? "); 

		// 时间过滤
		if (StringUtils.isNotBlank(time_filter)) {

			if ("today".equals(time_filter)) {
				sql.append("and date_format(a.beginTime,'%Y-%m-%d') = curdate() ");
			} else if ("tomorrow".equals(time_filter)) {
				sql.append("and date_format(a.beginTime,'%Y-%m-%d') = date_add(curdate(), interval 1 day) ");
			} else if ("weekend".equals(time_filter)) {
				sql.append("and weekday(a.beginTime) in (5,6) and a.beginTime >now()  ");
			}else if ("weekday".equals(time_filter)){
				sql.append("and weekday(a.beginTime) in (0,1,2,3,4) and a.beginTime >now() ");
			}else if("old".equals(time_filter)){
				sql.append("and a.beginTime <now() ");
			}
		}else {
			sql.append("and a.beginTime>now() ");
		}

		// 类型过滤
		if (StringUtils.isNotBlank(type_filter)) {
			String [] types = type_filter.split(",");
			type_filter = "";
			for(String type:types){
				type_filter += "'"+type+"',";
			}
			type_filter = type_filter.substring(0, type_filter.length()-1);
			sql.append("and a.typeId in (" + type_filter + ") ");
		}
		// 年龄过滤
		if (StringUtils.isNotBlank(age_filter)) {
			String[] ages = age_filter.split(",");
			int length = ages.length;
			if (length > 0) {
				sql.append("and (");
				for (int i = 0; i < length; i++) {
					String likeStr = "concat(',',a.ages,',') like '%," + ages[i] + ",%' ";
					if (i == 0) {// 第一个
						sql.append(likeStr);
					} else {
						sql.append("or " + likeStr);
					}
				}
				sql.append(") ");
			}
		}
		
		String[] fieldNames = null;
		// 距离过滤，必须传经纬度
		if (StringUtils.isNotBlank(distance_filter) && StringUtils.isNotBlank(lat) && StringUtils.isNotBlank(lon)) {
			sql.append("and round(6371.393*2*asin(sqrt(pow(sin((" + lat + "*pi()/180-a.activityAddressLat*pi()/180)/2),2)");
			sql.append("+cos(" + lat + "*pi()/180)*cos(a.activityAddressLat*pi()/180)* pow(sin((" + lon);
			sql.append("*pi()/180-a.activityAddressLon*pi()/180)/2),2)))*1000) ");
			sql.append("<= " + Integer.parseInt(distance_filter) * 1000 + " ");
			
			fieldNames = new String[]{ "id", "coverPicId", "title", "beginTime", "typeName", "organizationName", "adultPrice", "childPrice", "ages", "activityAddress", "activityAddressLon",
					"activityAddressLat", "distance" };
		}else{
			//少了一个distance
			fieldNames = new String[]{ "id", "coverPicId", "title", "beginTime", "typeName", "organizationName", "adultPrice", "childPrice", "ages", "activityAddress", "activityAddressLon",
 					"activityAddressLat"};
		}
		// 搜索关键词
		if (StringUtils.isNotBlank(key)) {
			sql.append("and a.title like '%" + key + "%' ")
			.append("or a.activityAddress like '%" + key + "%' ")
			.append("or a.ages like '%" + key + "%' ");
		}
		//JIAYU : BY BEGIN TIME DESC 
		sql.append("order by a.beginTime ASC");
		List<Object> values = new ArrayList<Object>();
		values.add(SysStatic.NORMALDELFLAG);
	

		return activityDAO.pageFindBySqlWithFieldNames(sql.toString(), values.toArray(), pager, Activity.class, fieldNames);
	}

	@Override
	public Activity getDetail(String activity_id, String lon, String lat) {

		StringBuilder sql = new StringBuilder();
		sql.append("select a.id,a.coverPicId,a.title,a.beginTime,aType.typeName as 'typeName',o.name as 'organizationName',");
		sql.append("a.adultPrice,a.childPrice,a.ages,a.activityAddress,a.activityAddressLon,");
		sql.append("a.activityAddressLat,a.contactPerson,a.contactNum,a.contactAddress,");
		sql.append("a.contactAddressLon,a.contactAddressLat,a.joinCount,a.joinLimitCount,a.detail,a.isAdultRecord,");
		sql.append("group_concat(ap.picId) as picIds");
		String[] fieldNames = null;
		if (StringUtils.isNotBlank(lat) && StringUtils.isNotBlank(lon)) {
			// 距离
			sql.append(",round(6371.393*2*asin(sqrt(pow(sin((" + lat + "*pi()/180-a.activityAddressLat*pi()/180)/2),2)");
			sql.append("+cos(" + lat + "*pi()/180)*cos(a.activityAddressLat*pi()/180)* pow(sin((" + lon);
			sql.append("*pi()/180-a.activityAddressLon*pi()/180)/2),2)))*1000) as 'distance' ");
			fieldNames = new String []{ "id", "coverPicId", "title", "beginTime", "typeName", "organizationName", "adultPrice", "childPrice", "ages", "activityAddress", "activityAddressLon",
					"activityAddressLat", "contactPerson", "contactNum", "contactAddress", "contactAddressLon", "contactAddressLat", "joinCount", "joinLimitCount", "detail", "picIds", "isAdultRecord","distance" };

		}else{
			fieldNames = new String[]{ "id", "coverPicId", "title", "beginTime", "typeName", "organizationName", "adultPrice", "childPrice", "ages", "activityAddress", "activityAddressLon",
					"activityAddressLat", "contactPerson", "contactNum", "contactAddress", "contactAddressLon", "contactAddressLat", "joinCount", "joinLimitCount", "detail", "picIds","isAdultRecord"};

		}

		sql.append(" from activity a ");
		sql.append("left join activity_type aType on aType.id = a.typeId ");
		sql.append("left join organization o on o.id = a.organizationId ");
		sql.append("left join activity_pic ap on ap.activityId = a.id ");
		sql.append("where a.deleteFlag = ? and a.id = ? ");
		sql.append("group by ap.activityId ");

		List<Object> values = new ArrayList<Object>();
		values.add(SysStatic.NORMALDELFLAG);
		values.add(activity_id);
		List<Activity> ac = activityDAO.pageFindBySqlWithFieldNames(sql.toString(), values.toArray(), null, Activity.class, fieldNames);
		if (ac != null && !ac.isEmpty()) {
			return ac.get(0);
		}
		return null;
	}


}
